package com.mihong.instance1;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import com.mihong.Initializer.ServerChannelInitializer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class NettyClient {
    private final String host;
    private final int port;

    public NettyClient() {
        this(0);
    }

    public NettyClient(int port) {
        this("localhost", port);
    }

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group) // 注册线程池
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                    //保持连接
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    //立即发送数据
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ServerChannelInitializer());// 绑定连接初始化器

            ChannelFuture cf = b.connect(this.host,this.port).sync(); // 异步连接服务器
            System.out.println("服务端连接成功..."); // 连接完成
            
            cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
            System.out.println("连接已关闭.."); // 关闭完成

        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
        }
    }
}
